package richy.com.floatingball;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * Created by rentianxin on 17-10-16.
 */

public class FloatingWindowManager {
    private WindowManager mWindowManager;
    private FloatingBallView mFloatingBallView;
    private boolean mHasAdded = false;

    public void addBallToWindow(FloatingBallService context) {
        if (mHasAdded) {
            Toast.makeText(context, "悬浮球已经开启", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mWindowManager == null) {
            mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            mFloatingBallView = new FloatingBallView(context);
        }
        int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
        int screenHeight = mWindowManager.getDefaultDisplay().getHeight();
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.x = screenWidth;
        layoutParams.y = screenHeight / 2;
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mFloatingBallView.setLayoutParams(layoutParams);
        mWindowManager.addView(mFloatingBallView, layoutParams);
        mHasAdded = true;
    }

    public void removeBallFromWindow() {
        if (!mHasAdded) {
            return;
        }
        mWindowManager.removeView(mFloatingBallView);
        mFloatingBallView = null;
        mWindowManager = null;
        mHasAdded = false;
    }

}
